import { Controller, Get, Param, Response } from "@nestjs/common";
import { FastifyReply } from "fastify";
import { ArticleService } from "src/article/article.service";
import { PageRenderService } from "./page.service";
import { ArticleContentDataType } from "src/article/enum/article-content-data";
import configuration from "src/common/configuration";

@Controller(["page", "pages", "ssr"])
export class PageRenderController {
  constructor(
    private readonly pageRenderService: PageRenderService,
    private readonly articleService: ArticleService,
  ) {}

  @Get("/article/:id")
  async article(
    @Response() response: FastifyReply,
    @Param("id") articleID: string | number,
  ) {
    response.header("content-type", "text/html;charset=utf-8");

    if (typeof articleID === "string") articleID = parseInt(articleID);
    if (isNaN(articleID)) {
      response.status(404);
      response.send("404");
      return;
    }
    const article = await this.articleService.getArticleByID(articleID, {
      getRichContent: true,
      contentType: ArticleContentDataType.HTML,
    });
    if (!article) {
      response.status(404).send(this.pageRenderService.html404());
      return;
    }

    article.title = article.title.replaceAll("<", "&lt;");
    const contentData = article.content;
    // const highlightCode = contentData.content.includes("<code>") ? true : false;
    const documentTitle = `${article.sort_name}——${article.title}`;
    const documentDescription = `${configuration.website.name}——文章——${article.author}——${documentTitle}`;
    const domain = (() => {
      const i = configuration.website.url.indexOf("//");
      return configuration.website.url.substring(i + "//".length);
    })();
    const html = `
        <!DOCTYPE html>
        <html lang="zh">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">

            <!-- 信息 -->
            <link rel="icon" href="/favicon.ico" type="image/x-icon" />
            <title>${documentTitle}</title>
            <meta name="author" content="${article.author}" />
            <meta
                name="description"
                content="${documentDescription}"
            />

            <!-- Facebook Open Graph -->
            <meta property="og:title" content="${documentTitle}" />
            <meta property="og:type" content="article">
            <meta property="og:url" content="${configuration.website.url}/pages/article/${article.id}">
            <meta property="og:image" content="${configuration.website.url}/favicon.png" />
            <meta property="og:site_name" content="${configuration.website.name}" />
            <meta
                property="og:description"
                content="${documentDescription}"
            />

            <!-- Twitter Cards -->
            <meta name=twitter:card content="summary" />
            <meta name=twitter:image content="${configuration.website.url}/favicon.png" />
            <meta name="twitter:title" content="${documentTitle}" />
            <meta name=twitter:description content="${documentDescription}" />
            <meta name="twitter:creator" content="@${article.author}" />
            <meta name="twitter:site" content="@${domain}" />

            <!-- style -->
            <link rel="stylesheet" href="/css/old/style.css">
            <link rel="stylesheet" href="/css/old/style-fit.css">
            <link rel="stylesheet" href="/css/old/article.css">

            <!-- 百度统计 -->
            <script src="/js/tongji.js"></script>
            <!-- Vue3 -->
            <script src="/js/vue/vue.global.prod.js"></script>
            <!-- WX JS SDK -->
            <script src="/js/wx.js"></script>
        </head>
        <body>
            <page-header></page-header>

            <div class="block-spacer"></div>
            <div class="block-spacer"></div>
            <main>
                <article>
                    <h1 class="article-title">${article.title}</h1>
                    <div class="article-author-container">
                        <span>作者：</span>
                        <a class="article-author" href="#">${article.author}</a>
                    </div>
                    <h4 class="article-date">${article.date}</h4>

                    <!-- <div class="block-spacer"></div> -->
                    <hr/>

                    ${contentData.content}
                </article>
            </main>

            <page-footer></page-footer>

            <script src="/js/http.js"></script>
            <script src="/js/old/component.js"></script>
            <script src="/js/style.js"></script>
            <script src="/js/nav.js"></script>
            <script src="/js/android.js"></script>
            <script>
              (async function() {
                const codeElements = document.getElementsByTagName("code");
                if (codeElements && codeElements.length !== 0) {
                  (function () {
                    const css = document.createElement("link");
                    css.rel = "stylesheet";
                    css.href = "/css/third/highlight.min.css";
                    document.head.appendChild(css);
                  })();
                  await new Promise((resolve) => {
                    const script = document.createElement("script");
                    script.src = "/js/third/highlight.min.js";
                    document.head.appendChild(script);
                    script.onload = function () {
                      resolve();
                    };
                  });
                  hljs.highlightAll();
                }
              })();
            </script>
        </body>
        </html>
    `;
    response.send(html);
  }
}
